package com.rightsidetech.http.wechatutil;

import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.rightsidetech.http.config.WechatConfig;
import lombok.extern.slf4j.Slf4j;


/**
 * @Package: com.rightsidetech.http.wechatutil
 * @ClassName: WechatSendMsgUtil
 * @Author: yinj
 * @CreateTime: 2021/12/20 15:53
 * @Description: 微信订阅消息发送
 */
@Slf4j
public class WechatMsgSendUtil {

    public static void sendMassage(WechatConfig wechatConfig, MsgTemplate template) {
        String params = "grant_type=client_credential&appid=" + wechatConfig.getAppId() + "&secret=" + wechatConfig.getSecret();
        String s = HttpUtil.get(WechatConfig.GET_ACCESS_TOKEN + params);
        JSONObject jsonObject = JSONObject.parseObject(s);
        String accessToken = jsonObject.getString("access_token");

        String requestUrl = WechatConfig.GET_SEND_MESSAGE;
        requestUrl = requestUrl.replace("ACCESS_TOKEN", accessToken);

        log.info(JSON.toJSONString(template));
        String result = HttpUtil.post(requestUrl, JSON.toJSONString(template), 5000);
        if (result != null) {
            JSONObject parse = JSONObject.parseObject(result);
            int errorCode = parse.getIntValue("errcode");
            String errorMessage = parse.getString("errmsg");
            if (errorCode == 0) {
                log.info("订阅消息发送成功");
            } else {
                log.info("订阅消息发送失败:" + errorCode + "," + errorMessage);
            }
        }
    }

}
